/*
 * 检查缓存时间
 * @param data
 * return true->、false->过期
 */
function checkCacheTime(data) {
  const newDate = new Date(),
      differ = Number(data['expire']) * 3600 * 1000;
  let rc = true,
      starDate = new Date(Number(data['date']));

  // console.log('newDate-time:', newDate - starDate);
  // console.log('differ:', differ);

  if (newDate - starDate >= differ) {
    rc = false;
    // console.log('Remove cache time');
  } else {
    // console.log('Print cache time：', starDate);
  }
  return rc;
}
/*
 * 设置缓存数据
 * @param key ->str
 * @param value -> {data:数据data,date:缓存开始的时间date,expire:小时为单位expire}
 */
function setCache(key, data) {
  const rs = getCache(key);
  if (!rs) {
    if (data) {
      data = data instanceof String ? data : JSON.stringify(data);
      localStorage.setItem(key, data);
      // console.log('设置数据:', rs);
    } else {
      // console.log('数据无效:', rs);
    }
  } else {
    // console.log('已经缓存数据了:', rs);
  }
}
/*
 * 获取缓存数据
 * @param key ->str
 * return data
 */
function getCache(key) {
  let rc = null;
  let obj = JSON.parse(localStorage.getItem(key));
  // console.log('obj', obj);
  if (obj && checkCacheTime(obj)) {
    rc = obj['data'];
  } else {
    removeCache(key);
  }
  return rc;
}

// 删除缓存数据
function removeCache(key) {
  localStorage.removeItem(key);
}

export {setCache, getCache, removeCache};